"use client";

import { useEffect, useState } from "react";
import i18next from "i18next";
import {
  initReactI18next,
  useTranslation as useTranslationOrg,
} from "react-i18next";
import resourcesToBackend from "i18next-resources-to-backend";
import { normalizeLanguageCode, getLanguageFileName } from "./setting";

i18next
  .use(initReactI18next)
  .use(
    resourcesToBackend((language: string) => {
      const fileName = getLanguageFileName(language);
      return import(`./locales/${fileName}.json`);
    })
  )
  .init({
    lng: undefined, // let detect the language on client side
  });

export function useTranslation(ns: string, options?: object) {
  // 只在浏览器环境中读取 localStorage
  const [lang, setLang] = useState(() => {
    if (typeof window !== "undefined") {
      const storedLang = localStorage.getItem("language") || "zh_CN";
      return normalizeLanguageCode(storedLang);
    }

    return "zh_CN"; // 服务器端渲染时使用默认值
  });

  const ret = useTranslationOrg(ns, options);
  const { i18n } = ret;

  const changeLanguage = (newLang: string) => {
    const normalizedLang = normalizeLanguageCode(newLang);
    setLang(normalizedLang);
    i18n.changeLanguage(normalizedLang);

    if (typeof window !== "undefined") {
      localStorage.setItem("language", newLang); // 存储原始语言代码
      // 更新 html 标签的 lang 属性
      const htmlLang = newLang === "zh_CN" || newLang === "zh" ? "zh" : "en";
      document.documentElement.lang = htmlLang;
    }
  };

  useEffect(() => {
    if (lang && typeof window !== "undefined") {
      i18n.changeLanguage(lang);
      localStorage.setItem("language", lang);
      const htmlLang = lang === "zh_CN" || lang === "zh" ? "zh" : "en";
      document.documentElement.lang = htmlLang;
    }
  }, [lang, i18n]);

  return { ...ret, changeLanguage, lang };
}
